package info.niwota.home.fm;

import info.niwota.home.R;
import instant.openvfs.home.Debug;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import x.java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class IntentEditActivity extends BaseFileActivity {
	private static final String LOG_TAG = "IntentEditActivity";

	private class AppInfo {
		//public ResolveInfo info;
		
		public String title;

		public Drawable icon;

		@Override
		public String toString() {
			return title;
		}
	}

	private class AppAdapter extends ArrayAdapter<AppInfo> {
		LayoutInflater mInflater;

		public AppAdapter(Activity ctx, ArrayList<AppInfo> activities) {
			super(ctx, 0, activities);
			// mInflater = activity.getLayoutInflater();
			mInflater = LayoutInflater.from(ctx);

		}

		@Override
		public View getDropDownView(int position, View convertView,
				ViewGroup parent) {
			return getView(position, convertView, parent, R.layout.list_item2);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getView(position, convertView, parent, R.layout.list_item);
		}
		
		private View getView(int position, View convertView, ViewGroup parent, int res) {
			final AppInfo ai = getItem(position);
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(res, parent,
						false);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.list_item_title);
				holder.icon =  (ImageView) convertView.findViewById(R.id.list_item_icon);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.title.setText(ai.title);
			holder.icon.setImageDrawable(ai.icon);
			//
			return convertView;
		}
	}

	private static class ViewHolder {
		ImageView icon;
		TextView title;
	}

	private final class LoadTask extends AsyncTask<Void, Void, AppAdapter> {
		@Override
		protected void onCancelled() {
			setProgressBarIndeterminateVisibility(false);
		}

		@Override
		protected void onPostExecute(AppAdapter result) {
			setProgressBarIndeterminateVisibility(false);
			spinner.setAdapter(result);
		}

		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected AppAdapter doInBackground(Void... params) {
			ArrayList<AppInfo> list = new ArrayList<AppInfo>();
			loadApplications(list);
			AppAdapter adapt = new AppAdapter(IntentEditActivity.this, list);
			return adapt;
		}

	}

	private EditText inputText;
	private EditText selectText;
	private Spinner spinner;
	private String path; // location to save new file
	private LoadTask loader;

	// private ArrayAdapter<AppInfo> spinnerAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTheme(android.R.style.Theme_Translucent_NoTitleBar);
		setContentView(R.layout.newintent);

		init();
	}

	private void init() {
		spinner = (Spinner) findViewById(R.id.newintent_openwith);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> av, View v, int pos,
					long id) {
				//
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		//
		try {
			if (loader == null) {
				loader = new LoadTask();
			} else {
				loader.cancel(true);
			}
			loader.execute();
		} catch (Exception e) {

		}
		//

		final Button confirmBtn = (Button) findViewById(R.id.newintent_confirm);
		final Button cancelBtn = (Button) findViewById(R.id.newintent_cancel);
		final ImageButton viBtn = (ImageButton) findViewById(R.id.newintent_voiceinput);
		final ImageButton fcBtn = (ImageButton) findViewById(R.id.newintent_filechoose);
		//
		final TextView pathText = (TextView) findViewById(R.id.newintent_path);
		inputText = (EditText) findViewById(R.id.newintent_input);
		selectText = (EditText) findViewById(R.id.newintent_uri);

		Uri data = getIntent().getData();
		path = data.getPath();
		pathText.setText(path);

		inputText.setText("");
		//
		confirmBtn.setOnClickListener(this);
		cancelBtn.setOnClickListener(this);
		viBtn.setOnClickListener(this);
		fcBtn.setOnClickListener(this);
		//
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newintent_voiceinput:
			startVoiceInputActivityForResult();
			break;
		case R.id.newintent_filechoose:
			startFileChooseActivityForResult();
			break;
		case R.id.newintent_confirm:
			doConfirm();
			break;
		case R.id.newintent_cancel:
			doCancel();
			break;
		default:
		}
	}

	private void doCancel() {
		setResult(RESULT_CANCELED);
		finish();
	}

	private void doConfirm() {
		try {
			String name = inputText.getText().toString();
			name = Utils.sanitize(name);
			URI uri = new URI(selectText.getText().toString());
			if (uri.isAbsolute() == false) {
				uri = new URI("file:" + path);
			}
			//
			File f = new File(path, name);
			if (f.exists()) {
				Toast.makeText(IntentEditActivity.this, "File exists",
						Toast.LENGTH_SHORT);
				return;
			}
			// save
			StringBuilder sb = new StringBuilder();
			// sb.append();
			f.setContent(sb.toString());
			//
			Intent data = new Intent();
			data.setData(Uri.parse(f.toURI().toString()));
			setResult(RESULT_OK, data);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(IntentEditActivity.this, e.getMessage(),
					Toast.LENGTH_LONG).show();
			setResult(RESULT_CANCELED);
		}
		//
		finish();
	}

	@Override
	protected void handleFileChooseActivityResult(String sel, Intent data) {
		if (Debug.DEBUG) {
			Log.v(LOG_TAG, "selected: " + sel);
		}
		selectText.setText(sel);
		// set default name if none exists
		if (TextUtils.isEmpty(inputText.getText())) {
			String p = Uri.parse(sel).getLastPathSegment();
			String n = (p == null || p.equals("/")) ? Utils.createName() : p;
			inputText.setText(n);
		}
	}

	@Override
	protected void handleVoiceInputActivityResult(String vi, Intent data) {
		inputText.setText(vi);
	}

	private void loadApplications(ArrayList<AppInfo> list) {
		PackageManager pm = getPackageManager();
		//
		Intent mi = new Intent(Intent.ACTION_MAIN, null);
		mi.addCategory(Intent.CATEGORY_LAUNCHER);

		final List<ResolveInfo> apps = pm.queryIntentActivities(mi, 0);
		Collections.sort(apps, new ResolveInfo.DisplayNameComparator(pm));
		if (Debug.DEBUG) {
			Log.d(LOG_TAG, "loadApplications: " + apps);
		}
		if (apps != null) {
			final int count = apps.size();
			list.clear();
			//
			if (Debug.DEBUG) {
				Log.d(LOG_TAG, "loadApplications: count: " + count);
			}
			//
			for (int i = 0; i < count; i++) {
				AppInfo info = new AppInfo();
				ResolveInfo ri = apps.get(i);
				info.title = ri.loadLabel(pm).toString();
				// ComponentName cn = new ComponentName(
				// ri.activityInfo.applicationInfo.packageName,
				// ri.activityInfo.name);
				// info.setActivity(cn, Intent.FLAG_ACTIVITY_NEW_TASK
				// | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				info.icon = ri.activityInfo.loadIcon(pm);
				
				list.add(info);
			}
		}
	}
}
